#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "http.h"
#include "log.h"

char *create_http_request(http_url *url)
{
    const char *request_tpl = "GET %s HTTP/1.1\r\n\
Host: %s\r\n\
Connection: Close\r\n\r\n";

    int size = strlen(request_tpl) + strlen(url->uri) + strlen(url->host) -4 + 1;
    
    char *http_request = (char *)malloc(size);

    sprintf(http_request, request_tpl, url->uri, url->host);

    debug_log("http_request\t%s\n", http_request);

    return http_request;
}

http_response_header *http_response_header_prase(const char *http_response_header_str, int len)
{
    char *str = strndup(http_response_header_str,len);
    char *str_p = str;

    http_response_header *http_res = (http_response_header *)malloc(sizeof(http_response_header));

    const char *s = "\r\n";
    int line = 0;

    while(true){
        if(strlen(str) <= 0){
            break;
        }

        char *sub_str = strstr(str,s);
        char *current_line = strndup(str,sub_str - str);

        line++;

        if(line == 1) {
            if(strcmp(current_line,"HTTP/1.1 200 OK") != 0) {
                error_log("http 状态码异常\n");
                exit(1);
            }

            http_res->http_code = 200;
        }else{
            char *p = strchr(current_line,':');

            if(p){
                if(strncmp(current_line,"Content-Length",p - current_line) == 0) {
                    http_res->content_length = atoi(p+2);
                } else if (strncmp(current_line,"Content-Type",p - current_line) == 0) {
                    http_res->content_type = strdup(p+2);
                }
            }
        }

        str += strlen(current_line) + 2;
    }

    free(str_p);
    printf("长度:%lu(%0.1fM)[%s]\n",http_res->content_length,(float) http_res->content_length/(1024*1024), 
           http_res->content_type);

    return http_res;
}
